package compilador.file;


import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import compilador.file.FileUtil;

public class FileUtil
{
	/** Retorna uma coleção contendo cada linha do arquivo */
	public static List<String> getLines(File wordsFile) throws FileNotFoundException
	{
		Scanner scanner = new Scanner(wordsFile);

		ArrayList<String> words = new ArrayList<String>();

		while( scanner.hasNextLine() ) {
            String line = scanner.nextLine();
            if(line == null || line.equals("")){
            	continue;
            }
			words.add(line);
		}

		return words;
	}

	public static void write(File running, String str) throws IOException
	{
		FileOutputStream fos = new FileOutputStream(running);
		fos.write(str.getBytes());
		fos.write('\n');
		fos.close();
	}

	public static void appendLine(String fileName, String contentToAppend) throws IOException
	{
		FileOutputStream fos = new FileOutputStream(fileName, true);
		fos.write(contentToAppend.getBytes());
		fos.write('\n');
		fos.close();
	}

	public static void makeFile(File file) throws IOException {
		if(! file.exists()){
			File dir = new File(file.getParent());
			if(! dir.exists()){
				dir.mkdirs();
			}
			file.createNewFile();
		}
	}

	public static void copy(File file, File newFile) throws IOException {
		final int BUFF_SIZE = 100000;
		final byte[] buffer = new byte[BUFF_SIZE];

		FileUtil.makeFile(file);

		boolean EOF;
		FileInputStream input;
		ObjectInputStream inputStream = null;
		FileOutputStream output;
		ObjectOutputStream outputStream = null;
		try{
			EOF = false;
			input  = new FileInputStream(file);
			inputStream = new ObjectInputStream(input);

			output = new FileOutputStream(newFile);
			outputStream = new ObjectOutputStream(output);

			while (! EOF) {
			    synchronized (buffer) {
			        int amountRead = inputStream.read(buffer);
			        if (amountRead == -1) {
			        	break;
			        }

			        outputStream.write(buffer, 0, amountRead);
			    }
			}
		} catch (EOFException e){
			EOF = true;
		}

		if(outputStream == null){
			output = new FileOutputStream(file);
			outputStream = new ObjectOutputStream(output);
		}
		if(inputStream != null)
			inputStream.close();

	}
}
